package com.angular.useradmin.user.service.impl;

import com.angular.useradmin.user.common.exceptionhandler.MyException;
import com.angular.useradmin.user.entity.New;

import com.angular.useradmin.user.entity.vo.FiledArrays;
import com.angular.useradmin.user.mapper.NewMapper;
import com.angular.useradmin.user.service.NewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 许根银
 * @since 2023-01-05
 */
@Service

@Slf4j
public class NewServiceImpl extends ServiceImpl<NewMapper, New> implements NewService {


    /**
     * copy表数据
     *
     * @return
     */
    @Override
    public boolean copyTable() {
        // truncate table 成功0  失败-1 除非表不存在
        baseMapper.deleteTable();
        return baseMapper.copyTable();
    }

    /**
     * 获取两张表join值
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getQueryData() {
        return baseMapper.getQueryAllData();
    }

    /**
     * 获取所有表名
     *
     * @return
     */
    @Override
    public String[] getAllTableName() {
        return baseMapper.getAllTableName();
    }

    /**
     * 获取所有字段名
     *
     * @return
     */
    @Override
    public String[] getAllFieldName(String tableName) {
//       字段名是key 数据——>字段名 :  Map<String fileName,List<Map<String, Object>>

        return baseMapper.getAllFieldName(tableName);
    }



    /**
     *
     * @param tableName 表名
     * @param current   当前页
     * @param limit     没页多少条数据
     * @return      rows 每页的数据list
     *              totalPage 总页数
     */

    @Override
    public Map<String, Object> getAllValue(String tableName, int current, int limit) {
        List<Map<String, Object>> all = baseMapper.getAll(tableName);


        Map<String, Object> map =new HashMap<>();
        map.put("rows", all.stream()
                .skip(  (long) (current - 1) * limit)
                .limit(limit)
                .collect(Collectors.toList()));
        map.put("totalPage",Math.ceil(1.0*all.size()/limit));
        map.put("total",all.size());
        return map;
    }



    /**
     * @param filedArrays tableMaster    A表字段名数组
     *                    tableNew       B表字段名数组
     *                    queryTableName 数据源表名
     *                    newTableName   插入数据的表名
     *                    默认，如果存在事务，则支持当前事务；不存在，则开启一个新事务
     *                    事务被处理为顺序执行
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE)
    public boolean translate(FiledArrays filedArrays) {

        List<String> master = Arrays.stream(filedArrays.getTableMaster()).collect(Collectors.toList());  //A表字段
        List<String> news = Arrays.stream(filedArrays.getTableNew()).collect(Collectors.toList());   //B表字段
        List<String> fieldName = news.stream().filter(master::contains).collect(Collectors.toList());    //相同的字段

        HashMap<String, Object> lastMap = new HashMap<>();//数据容器
        HashMap<String, String[]> initMap = new HashMap<>();//初始化容器
        int index = 1;
        int translate = 0;

        for (int i = 0; i < fieldName.size(); i++) {
            String[] userMessages = baseMapper.getAllValue(filedArrays.getQueryTableName(), fieldName.get(i));
            initMap.put(fieldName.get(i), userMessages);
            while (initMap.size() == fieldName.size() && index <= userMessages.length) {
                for (String key : initMap.keySet()) {
                    String[] strings = initMap.get(key);
                    lastMap.put(key, strings[index - 1]);
                    if (lastMap.size() == fieldName.size()) {
                        translate += baseMapper.translate(lastMap, filedArrays.getNewTableName());
                        log.info("已传入{}条，本次已传入数据——>{},", translate, lastMap);
                        lastMap.clear();
                    }
                }
                index++;
            }

        }
        if (translate < 0) {
            throw new MyException(2000, "未能成功插入");
        }
        return true;
    }


}